<?php defined('BASEPATH') || exit('No direct script access allowed');

use EasyWeChat\Foundation\Application;
use Grafika\Grafika;
use Grafika\Color;
/**
 *  controller 仅作为小型活动处理
 */
class Activity extends Front_Controller
{

    private $_sessionUserKey = 'jinrong_user_phone';
    private $_booksArray = ['1'=>"小王子",'1'=>"长颈鹿不会跳舞",'1'=>"能干的小海狸",'1'=>"伊索寓言",];
    private $_wxUserKey = 'jindi_wechat_user';
    private $_wechatUser = null;
    private $_urlMiddle = 'activity';
    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->driver('cache');
        $this->load->library('user_agent');
        $this->_wechatUser = $this->session->userdata($this->_wxUserKey);
    }

    /**
     * [fangJinSuo 房金所活动首页]
     * @author [fengchen]
     * @DateTime 2017-02-23T14:20:10+0800
     * @return   [type]                   [description]
     */
    public function fangJinSuo() {
        
        $data = [];
        $this->load->view('activity/index', $data);
    }
    /**
     * [subFangJinSuo 房金所数据提交处理]
     * @author [fengchen]
     * @DateTime 2017-02-23T14:53:15+0800
     * @return   [type]                   [description]
     */
    public function subFangJinSuo(){

        // 加载模型
        $this->load->model('activity_model');
        $get = $this->input->get();
        
        if (!empty($get)) {
            $mobile = $get["phone"];
            // 根据mobile查询数据库
            $arr = $this->activity_model->find_by(['mobile' => $mobile]);

            $data["has_fang"] = $get["nums"];
            $data["yzm"] = $get["code"];
            // 验证是否正确
            if (!$this->verifyPhoneCode($mobile, $data["yzm"])) {
                echo json_encode(['code'=>400, 'msg'=>"验证码不正确！"]);
                exit;
            }else{
                $data["is_checked"] = 1;
            }
            
            $result = $this->activity_model->update($arr->id, $data);
            if ($result) {
                echo json_encode(['code'=>200, 'msg'=>"申请已提交成功"]);
                exit;
            }else{
                echo json_encode(['code'=>200, 'msg'=>"申请提交失败"]);
                exit;
            }
        }
        
    }
    /**
     * 验证 手机验证码
     * @param  Int $mobile    手机号码
     * @param  Int $phoneCode 验证码
     * @return Boolean
     */
    private function verifyPhoneCode($mobile, $phoneCode) {
        $result = false;
        $phoneCodeArr = $this->phoneCodeArr();
        if (isset($phoneCodeArr[$mobile])) {
            if ($phoneCodeArr[$mobile]['code'] == $phoneCode) {
                $phoneCodeArr[$mobile]['status'] = 1;
                $this->session->set_userdata('fjs_phone_code', $phoneCodeArr);
                $result = true;
            }
        }
        return $result;
    }
    /**
     * ajax 发送短信验证码给手机号
     */
    public function ajaxSendCode() {
//        echo json_encode(['status'=>'ok']);exit();
        $get = $this->input->get();
        $mobile = $get['mobile'];
        if (!$this->verifyMobile($mobile)) {
            echo json_encode(['status'=>'号码错误']);
            exit;
        }
        // 发送验证码时入库
        $this->load->model('activity_model');
        $this->load->model('Activityfinanceregister_model');
        // 金融项目和其他活动区分开
        if(isset($get['activity_name']) && $get['activity_name'] == "jinrong"){
            $qd = $get['qd'];
            $this->load->model('mohe/financesources_model');
            $source = $this->financesources_model->find_by(['code'=>$qd]);
            $arr = $this->Activityfinanceregister_model->find_by(['mobile' => $mobile]);
            if(!empty($arr)){
                $jData['lastlogin'] = date("Y-m-d H:i:s");
                $this->Activityfinanceregister_model->update($arr->id, $jData);
            }else{
                $jData['mobile'] = $mobile;
                $jData['source'] = !empty($source->id) ? $source->id : "0";
                $jData['createtime'] = date("Y-m-d H:i:s");
                $this->Activityfinanceregister_model->insert($jData);
            }
        }else{
            $data["activity_name"] = !empty($get['activity_name']) ? $get['activity_name'] : "房金所";
            $data["mobile"] = $mobile;
            $data['create_time'] = date("Y-m-d h:i:s");
            $data["is_checked"] = 0;
            $arr = $this->activity_model->find_by(['mobile' => $mobile,'activity_name'=>$data["activity_name"]]);
            if(!empty($arr)){
                $this->activity_model->update($arr->id, $data);
            }else{
                $this->activity_model->insert($data);
            }
        }
        // 金融产品调用新的短信接口
        if(isset($get['activity_name']) && $get['activity_name'] == "jinrong"){
//            $rebackCode = $this->sendCode($mobile , 1);
            $rebackCode = $this->sendCode($mobile);
        }else{
            $rebackCode = $this->sendCode($mobile);
        }
        // 返回
        if($rebackCode->code == 2){
            echo json_encode(['status'=>'ok']);
        }else{
            echo json_encode(['status'=>'验证码发送失败~'.$rebackCode->code]);

        }
    }
    /**
     * [sendCode 发送验证码]
     * @author [author]
     * @DateTime 2017-02-23T15:57:42+0800
     * @param    [type]                   $mobile       [description]
     * @param    string                   $buildingCode [description]
     * @return   [type]                                 [description]
     */
    private function sendCode($mobile , $type="") {
        $code = $this->creatCodeByRand();

        $phoneCode = $this->phoneCodeArr();
        $phoneCode[$mobile] = ['code'=>$code, 'status'=>0];
        $this->session->set_userdata('fjs_phone_code', $phoneCode);
        $content = "您的验证码为：".$code."，请在页面填写验证码完成验证。（如非本人操作，可不予理会）";
        if(!empty($type) && $type == 1){
            $rebackCode = $this->sendSmsNew($mobile, $content);
        }else{
            $rebackCode = $this->sendSMS($mobile, $content);
        }
        return $rebackCode;
    }
    //生成验证码
    private function creatCodeByRand(){
        $token = '';
        $len = 6;
        for ($i = 0; $i < $len; $i++)
        $token .= chr(mt_rand(48, 57));
        return $token;
    }
    /**
     * 短信接口
     * @param  int $mobile  手机号码
     * @param  string $content 短信内容
     * @return boolean          
     */
    private function sendSMS($mobile, $content) {
        $post_url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
        $smsData = array(
            'account'=>'cf_shmkj',
            'password'=>'shmkj123',
            'mobile'=>$mobile,
            'content'=>$content,
        );
        if (is_fang90_server_name()) {
            $smsData['account'] = 'cf_youxwl';
            $smsData['password'] = 'e10adc3949ba59abbe56e057f20f883e';
        }
        $this->load->library('curl', $post_url);
        $this->curl->post($smsData);
        $returnStr = $this->curl->execute();
        if (!empty($returnStr)) {
            $obj = simplexml_load_string($returnStr);
            return $obj;
        }
    }
    private function sendSmsNew($mobile, $content){
        $post_url = "http://sms.10690221.com:9011/hy/";
        $smsData = array(
            'uid'=>'506995',
            'auth'=>md5('xacssioo05'),
            'mobile'=>$mobile,
            'msg'=>urlencode($content),
            'expid'=>0,
            'encode'=>'utf-8'
        );
        $this->load->library('curl', $post_url);
        $this->curl->post($smsData);
        $returnStr = $this->curl->execute();
        if (!empty($returnStr) && stripos($returnStr, ',') !== false) {
            $arr = explode(',',$returnStr);
            return (object)['code'=>2,'msgid'=>$arr[1]];
        }else{
            return (object)['code'=>$returnStr];
        }
    }
    /**
     * 验证手机号规则
     * @param int $mobile 手机号码
    */
    public function verifyMobile($mobile) {
        $return = false;
        // 正则手机或固定电话
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        $isMob = "/^1[3-5,7,8]{1}[0-9]{9}$/";
        if(preg_match($isMob, $mobile) || preg_match($isTel, $mobile)) {
            $return = true;
        }
        return $return;
    }
    private function phoneCodeArr() {
        if ($this->session->has_userdata('fjs_phone_code')) {
            return $this->session->userdata('fjs_phone_code');
        }
        return [];
    }

    public function server(){
        dump($_SERVER);exit();
    }
    /**
     * [jinrong 金融贷款项目投放页面]
     * @return [type] [description]
     */
    public function jinrong(){
        redirect('/');
        exit();
        $get = $this->input->get();
        $ids = isset($get['id']) ? $get['id'] : '';
        $qd = isset($get['qd']) ? $get['qd'] : 'other';
        $nb = isset($get['nb']) ? $get['nb'] : '';
        $where = "deleted = 0 and status = 1";
        if (empty($ids)) {
            // 默认调整到上海楼盘列表
            
        }else{
            $ids = str_replace("，",",",$ids);
            $where .= " AND id in ($ids)";
        }
        if(!empty($nb) && $nb == 1){
            $data['nb'] = 1;
        }
        if($this->agent->platform != "iOS"){
            $where .= " AND agent != 3";
        }
        $isLogin = empty($this->session->userdata($this->_sessionUserKey)) ? '' : $this->session->userdata($this->_sessionUserKey);
        $this->load->model('Activityfinance_model');
        $dataArr = $this->Activityfinance_model->where($where)->order_by('sort',"ASC")->find_all();
        $list = [];
        if($dataArr){
            foreach($dataArr as $key => $value){
                $list[$value->type][] = $value;
            }
        }
        $data['data'] = $list;
        $data['isLogin'] = $isLogin;
        $data['qd'] = $qd;
//        dump($data);exit();
//        $this->load->view('activity/jinrong', $data);
        $this->load->view('activity/finance', $data);
    }

    public function finance(){
        redirect('/');
        exit();
        $get = $this->input->get();
        $qd = isset($get['qd']) ? $get['qd'] : 'other';
        $isLogin = empty($this->session->userdata($this->_sessionUserKey)) ? '' : $this->session->userdata($this->_sessionUserKey);
        if(!empty($isLogin)){
            redirect("/Activity/jinrong?qd=".$qd);
        }
        $data['qd'] = $qd;
        $this->load->view('activity/yqd', $data);
    }
    /**
     * 金融登录
     */
    public function jrLogin(){
        $get = $this->input->get();
        $mobile = $get['mobile'];
        if (!$this->verifyMobile($mobile)) {
            echo json_encode(['status'=>'号码错误']);
            exit;
        }
        // 号码入库
        $this->load->model('activity_model');

        $isLogined = $this->activity_model->find_by(['mobile'=>$mobile,'activity_name'=>"金融贷款"]);
        if(!empty($isLogined)){
            $this->session->set_userdata($this->_sessionUserKey, $mobile);
            echo json_encode(['status'=>'ok']);exit();
        }
        $data["activity_name"] = "金融贷款";
        $data["mobile"] = $mobile;
        $data['create_time'] = date("Y-m-d h:i:s");
        $res = $this->activity_model->insert($data);
        // 返回
        if($res){
            $this->session->set_userdata($this->_sessionUserKey, $mobile);
            echo json_encode(['status'=>'ok']);exit();
        }else{
            echo json_encode(['status'=>'err']);exit();
        }
    }

    public function sessions() {
        $get = $this->input->get();
        $mobile = $get['mobile'];
        if(empty($mobile)){
            echo "缺少号码参数";exit();
        }
        $this->session->unset_userdata($this->_sessionUserKey);
        $this->load->model('Activityfinanceregister_model');
        $this->Activityfinanceregister_model->delete_where("mobile = '$mobile'");
        dump($this->session->userdata());
        echo APPPATH.'cache/ci3_sessions';
    }

    /**
     * h5记录访问日志
     */
    public function html5(){

        $ip_address = $this->input->ip_address();
        $userAgent = $this->input->user_agent();
        $logStr = date("Y-m-d H:i:s")."#html5#{$ip_address}#{$userAgent}";
        view_html5_log($logStr);
        $this->cache->redis->increment("jindi_html5_view_nums_1");
        $config = [
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
        ];
        $app = new Application($config);
        $js = $app->js;
        $view_nums = $this->cache->redis->get("jindi_html5_view_nums_1");
        $data['view_nums'] = $view_nums;
        $data['js'] = $js;
        $this->load->view('activity/jindi-1', $data);
    }

    /**
     * 事件日志记录
     */
    public function eventLog(){
        $get = $this->input->get();
        $event_name = !empty($get['eventName']) ? $get['eventName'] : "贷款";
        $this->load->library('Mobile-Detect/Mobile_Detect', null, 'mobile_Detect');
        $ip_address = $this->input->ip_address();
        $userAgent = $this->input->user_agent();
        // 浏览设备类型 1pc 2mobile 3table 9robot
        $broswerType = ($this->mobile_Detect->isMobile() ? ($this->mobile_Detect->isTablet() ? 3 : 2) : 1);
        $referrer = strlen($this->agent->referrer()) > 255 ? substr($this->agent->referrer(), 0, 255) : $this->agent->referrer();
        if ($this->agent->is_robot) {
            // 机器人
            $broswerType = '9';
        }
        $data = array(
            'event_name'=>$event_name,
            'ip_address' => $ip_address,
            'source_url' => $referrer,
            'broswer_type' => $broswerType,
            'user_agent' => $userAgent,
            'broswer' => $this->agent->browser,
            'os_type' => $this->agent->platform,
            'visit_time'=>date("Y-m-d H:i:s", time())
        );
        $this->load->model('activitylog_model');
        $this->activitylog_model->insert($data);
        echo json_encode(['status'=>'ok']);exit();
    }

    /**
     * 金地第二个H5
     */
    public function html5two(){

        $this->cache->redis->increment("jindi_html5_view_nums_2");
        $config = [
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
        ];
        $app = new Application($config);
        $js = $app->js;
        $view_nums = $this->cache->redis->get("jindi_html5_view_nums_2");
        $data['view_nums'] = $view_nums;
        $data['js'] = $js;
        $this->load->view('activity/jindi-2', $data);
    }
    public function html5reg(){
        $get = $this->input->get();
        $mobile = $get['mobile'];
        if (!$this->verifyMobile($mobile)) {
            echo json_encode(['status'=>'号码错误']);
            exit;
        }
        // 号码入库
        $this->load->model('activity_model');

        $isLogined = $this->activity_model->find_by(['mobile'=>$mobile,'activity_name'=>"金地全家福报名"]);
        if(!empty($isLogined)){
            echo json_encode(['status'=>'ok']);exit();
        }
        $data['yzm'] = $get['username'];
        $data["activity_name"] = "金地全家福报名";
        $data["mobile"] = $mobile;
        $data['create_time'] = date("Y-m-d h:i:s");
        $res = $this->activity_model->insert($data);
        // 返回
        if($res){
            echo json_encode(['status'=>'ok']);exit();
        }else{
            echo json_encode(['status'=>'err']);exit();
        }
    }

    /**
     * 金地第三个H5
     */
    public function html5three(){

        $this->oauth(__FUNCTION__);
        $this->cache->redis->increment("jindi_html5_view_nums_3");
        $config = [
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
        ];
        $app = new Application($config);
        $js = $app->js;
        $view_nums = $this->cache->redis->get("jindi_html5_view_nums_3");
        $data['view_nums'] = $view_nums;
        $data['js'] = $js;
        $data['books'] = $this->_booksArray;
        // 获取已录音时长
        $this->load->model('activitytape_model');
        $list = $this->activitytape_model->where(['deleted'=>0])->find_all();
        $res = [];
        if($list){
            foreach($list as $key => $value){
                $res[$value->book][] = explode(":", $value->duration)[2];
            }
        }
        $totalpj = 6*60;
        for($i = 1;$i< 5;$i++){
            if(!empty($res[$i])){
                $result[$i]['orig'] = $this->getTime(array_sum($res[$i]));
                // 获取秒数
                $arr = explode(":", $result[$i]['orig']);
                $result[$i]['second'] = $second = $arr[0]*60+$arr[1];
                $result[$i]['percent'] = round(($second/$totalpj)*100).'%';
            }else{
                $result[$i]['orig'] = "0";
                $result[$i]['second'] = '0';
                $result[$i]['percent'] = "0";
            }
        }
        $data['books'] = $result;
//        dump($data);exit();
        $this->load->view('activity/jindi-3', $data);
    }

    /**
     * 发布录音
     */
    public function storeVoice(){
        $get = $this->input->get();
        $serverId = $get['serverId'];
        $book = $get['book'];
        $wechatOpenid = $this->_wechatUser['id'];
        // 查询当前用户是否已经参与过录音
        $this->load->model('activitytape_model');
        $record = $this->activitytape_model->find_by(['openid'=>$wechatOpenid,'deleted'=>0]);
        if(!empty($record)){
            $callback = array(
                'code' => 405,
                'msg' => '您已经参与过录音了哦',
            );
            echo json_encode($callback);
            exit();
        }
        if(empty($serverId)){
            $callback = array(
                'code' => 403,
                'msg' => '没有serverId',
            );
            echo json_encode($callback);
            exit();
        }
        $config = [
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
        ];
        $app = new Application($config);
        $temporary = $app->material_temporary;
        $content = $temporary->getStream($serverId);
        $path = "/mnt/data/www/udianfang/public/wxVoice/' . $serverId";
        $filePath = "/mnt/data/www/udianfang/public/wxVoice/" . $serverId . ".amr";
        file_put_contents($filePath, $content);
        // 将amr文件转化为MP3格式
//        exec("/mnt/data/www/udianfang/public/ffmpeg -i /mnt/data/www/udianfang/public/wxVoice/".$serverId.".amr /mnt/data/www/udianfang/public/wxVoice/".$serverId.".mp3 2>&1",$output, $return_val);
//        $this->html5errlog(json_encode($output));
//        $this->html5errlog($return_val);
        exec("/mnt/data/www/udianfang/public/ffmpeg -i /mnt/data/www/udianfang/public/wxVoice/".$serverId.".amr /mnt/data/www/udianfang/public/wxVoice/".$serverId.".mp3");
        // 获取MP3音频的时长
        $duration = exec("/mnt/data/www/udianfang/public/ffmpeg -i /mnt/data/www/udianfang/public/wxVoice/".$serverId.".mp3 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");//总长度
        // 构造数组入库
        $data = array(
            'openid'=>$wechatOpenid,
            'serverid'=>$serverId,
            'book'=>$book,
            'duration'=>$duration
        );
        $res = $this->activitytape_model->insert($data);
        // 返回值
        if($res){
            $msg = "上传成功";
        }else{
            $msg = "上传失败";
        }
        $callback = array(
            'code' => 200,
            'msg' => $msg
        );
        echo json_encode($callback);
        exit();

    }
    /**
     * 微信登录验证
     * @param  string $action 回调的action
     * @return void
     */
    private function oauth($action) {
        // 未登录
        if (!$this->session->has_userdata($this->_wxUserKey)) {
            $config = [
                'app_id' => config_item("wechat.app_id"),
                'oauth' => [
                    'scopes'   => ['snsapi_base'],//snsapi_userinfo
                    'callback' => '/'.$this->_urlMiddle.'/wechatOauthBack',
                ],
            ];
            $app = new Application($config);
            $oauth = $app->oauth;

            $this->session->set_userdata('target_url', '/'.$this->_urlMiddle.'/'.$action);
            $oauth->redirect()->send();
        }
    }

    /**
     * 微信登录验证回调
     * @return void
     */
    public function wechatOauthBack() {
        $config = [
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
        ];
        $app = new Application($config);
        $oauth = $app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        $userArr = $user->toArray();
        $this->session->set_userdata($this->_wxUserKey, $userArr);
        $targetUrl = empty($this->session->userdata('target_url')) ? '/' : $this->session->userdata('target_url');
//        $wechatUser = $app->user->get($userArr['id']);
//        $this->wechatusers_model->subscribe($wechatUser);
        redirect($targetUrl);
    }


    private function html5errlog($data) {
        if (empty($data)) return false;

        $path = APPPATH.'logs'.DIRECTORY_SEPARATOR.'html5errlog';
        file_exists($path) OR mkdir($path, 0755, TRUE);

        $filename = 'h5_log_'.date("Y-m-d").'.txt';
        return file_put_contents($path.DIRECTORY_SEPARATOR.$filename, $data.PHP_EOL, FILE_APPEND | LOCK_EX);
    }

    /**
     * 获取四本书的累计录音时长
     */
    public function getTotalDuration(){

        $this->load->model('activitytape_model');
        $list = $this->activitytape_model->where(['deleted'=>0])->find_all();
        $res = [];
        if($list){
            foreach($list as $key => $value){
                $res[$value->book][] = explode(":", $value->duration)[2];
            }
        }
        for($i = 1;$i< 5;$i++){
            if(!empty($res[$i])){
                $data[$i] = $this->getTime(array_sum($res[$i]));
            }else{
                $data[$i] = "0";
            }
        }

        dump($data);exit();
    }

    /**
     * 录音时间友好化
     * @param $second
     * @return string
     */
    private function getTime($second){
        $time = gmdate("i:s", $second);
        // 如果第一位是0 则去掉
        if(substr($time , 0 , 1) == '0'){
            return substr($time , 1);
        }else{
            return $time;
        }

    }

    /**
     * 金地第四个H5
     */
    public function html5four(){
        $config = [
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
        ];
        $app = new Application($config);
        $js = $app->js;

        $this->cache->redis->increment("jindi_html5_view_nums_4");
        $view_nums = $this->cache->redis->get("jindi_html5_view_nums_4");
        $data['view_nums'] = $view_nums;
        $data['js'] = $js;
        $this->load->view('activity/jindi-4', $data);
    }

    public function mergePic(){


        $oname = $_POST['oname'];
        $ocon = $_POST['ocon'];
        $nameToLeft = $_POST['ntleft'];
        $conToLeft = $_POST['ctleft'];
        $public = realpath(APPPATH .'../public');
        $path = $public."/html5/";
        if(!is_dir($path)){
            mkdir($path);
        }
        header("Content-type: text/html; charset=utf-8");
        $imgpath = time().uniqid() . '.jpg';
        $editor = Grafika::createEditor();
        $editor->open($image , $public.'/page5.jpg');
        $editor->text($image , "我是".$oname,38,$nameToLeft,810,new Color("#fff"),$public.'/yuweishufa.TTF',0);
        $editor->text($image , $ocon,38,$conToLeft,890,new Color("#fff"),$public.'/yuweishufa.TTF',0);
        $editor->save($image,$path.$imgpath);
        echo json_encode(['img'=>site_url()."/html5/".$imgpath]);exit();

    }

    public function tanchuang(){
        $get = $this->input->get();
        $data['link'] = $get['link'];
        $this->load->view('activity/tanchuang',$data);
    }
    public function tanchuang2(){
        $get = $this->input->get();
        $data['mobile'] = $get['mobile'];
        $this->load->view('activity/tanchuang2',$data);
    }
    public function subTanChuang(){
        // 加载模型
        $this->load->model('Activityfinanceregister_model');
        $get = $this->input->get();

        if (!empty($get)) {
            $mobile = $get["phone"];
            // 根据mobile查询数据库
            $arr = $this->Activityfinanceregister_model->find_by(['mobile' => $mobile]);
            $data["yzm"] = $get["code"];
            // 验证是否正确
            if (!$this->verifyPhoneCode($mobile, $data["yzm"])) {
                echo json_encode(['code'=>400, 'msg'=>"验证码不正确！"]);
                exit;
            }
            $data["checked"] = 1;
            $data["lastlogin"] = date("Y-m-d H:i:s");
            $result = $this->Activityfinanceregister_model->update($arr->id, $data);
            if ($result) {
                $this->session->set_userdata($this->_sessionUserKey, $mobile);
                echo json_encode(['code'=>200, 'msg'=>"提交成功"]);
                exit;
            }else{
                echo json_encode(['code'=>200, 'msg'=>"提交失败"]);
                exit;
            }
        }
    }

    /**
     * 金地第五个H5
     */
    public function html5five(){
        $config = [
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
        ];
        $app = new Application($config);
        $js = $app->js;

        $this->cache->redis->increment("jindi_html5_view_nums_5");
        $view_nums = $this->cache->redis->get("jindi_html5_view_nums_5");
        $data['view_nums'] = $view_nums;
        $data['js'] = $js;
        $this->load->view('activity/jindi-5', $data);
    }
    /**
     * 翡翠联盟海报合成
     */
    public function merge(){
        $get = $this->input->get();
        $keyword = urldecode($get['keyword']);
        $username = urldecode($get['username']);
        $keyToTop = $get['keyToTop'];
        $keyToLeft = $get['keyToLeft'];
        $nameToTop = $get['nameToTop'];
        $nameToLeft = $get['nameToLeft'];
        $public = realpath(APPPATH .'../public');
        $path = $public."/fclm/";
        if(!is_dir($path)){
            mkdir($path);
        }
        header("Content-type: text/html; charset=utf-8");
        $imgpath = time().uniqid() . '.jpg';
        $editor = Grafika::createEditor();
        $editor->open($image , $public.'/fclm/bg'.mt_rand(1, 4).'.jpg');
        if(preg_match('/[\x{4e00}-\x{9fa5}]/u', $username)>0) {
            $editor->text($image , $username,38,$nameToLeft,$nameToTop,new Color("#fff"),$public.'/fclm/lthj.TTF',0);
            $editor->text($image , $keyword,38,$keyToLeft,$keyToTop,new Color("#fff00"),$public.'/fclm/lthj.TTF',0);
        }else{
            $editor->text($image , $username,38,$nameToLeft,$nameToTop,new Color("#fff"),$public.'/fclm/Skia.ttf',0);
            $editor->text($image , $keyword,38,$keyToLeft,$keyToTop,new Color("#fff00"),$public.'/fclm/Skia.ttf',0);
        }

        $editor->save($image,$path.$imgpath);
//        echo json_encode(['img'=>site_url()."/fclm/".$imgpath]);exit();
        $callback = $get['callback'];
        echo $callback.'('.json_encode(['img'=>site_url()."/fclm/".$imgpath]).')';exit();
    }



}